import axios from "axios";
import Qs from "qs";
import {
	Message,
	Loading
} from "element-ui";
import router from "../router/index";
import common from "../utils/common"
import {
	saveAs
} from 'file-saver'

let loading;

function startLoading() {
	//使用Element loading-start 方法
	loading = Loading.service({
		target: document.querySelector(".custom-loading"),
		lock: true,
		background: "rgba(0, 0, 0, 0.8)",
		text: '拼命加载中',
		spinner: 'el-icon-loading'
	});
}

function endLoading() {
	//使用Element loading-close 方法
	loading.close();
}

let needLoadingRequestCount = 0;
export function showFullScreenLoading() {
	if (needLoadingRequestCount === 0) {
		startLoading();
	}
	needLoadingRequestCount++;
}

export function tryHideFullScreenLoading() {
	if (needLoadingRequestCount <= 0) return;
	needLoadingRequestCount--;
	if (needLoadingRequestCount === 0) {
		endLoading();
	}
}

axios.defaults.headers['client'] = 'admin'

//超时时间10秒
axios.defaults.timeout = 10000;
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
axios.defaults.withCredentials = true


axios.defaults.baseURL = "/server"
//上传一个文件
const upFileUrl = "/server/api/app/file/up"
//上传多个文件
const upFilesUrl = "/server/api/app/file/ups"
const uploadHeaders = () => {
	return {
		client: 'admin',
		authorization: getToken(),
	}
}
/**
 * 获取token
 */
function getToken() {
	let token = localStorage.getItem("token")
	if (token) {
		return "Bearer_" + token
	} else {
		return "";
	}
}

// http request 拦截器
axios.interceptors.request.use(
	config => {
		console.info("request拦截器", config)
		config.headers['Content-Type'] = 'application/json;charset=utf-8'
		config.headers['authorization'] = getToken();
		showFullScreenLoading();
		return config;
	},
	error => {
		common.msgError(error.message)
		return Promise.reject(error);
	}
);

//http response拦截器
axios.interceptors.response.use(
	response => {
		// 如果返回的状态码为200，说明接口请求成功，可以正常拿到数据
		// 否则的话抛出错误
		console.info("response拦截器", response)
		if (response.headers["content-type"] == 'application/octet-stream;charset=UTF-8') {
			tryHideFullScreenLoading();
			let blob = new Blob([response.data], {
				type: 'application/zip'
			});
			saveAs(blob, decodeURI("闫伟.zip"))
			return Promise.resolve(response);
		}
		if (response.status === 200) {
			tryHideFullScreenLoading();
			let result = response.data
			let code = result.code
			if (code == 200) {
				let config = response.config
				if (config.method == 'post' || config.method == 'put' || config.method == 'delete') {
					common.msgSuccess("操作成功")
				}
				return Promise.resolve(result.result);
			} else {
				if (code == 401) {
					if (router.currentRoute.path != '/login') {
						//清除storage中数据
						localStorage.clear();
						sessionStorage.clear();
						//跳转登录页
						router.replace("/login");
					}
					common.msgWarn(result.message)
				} else if (result.code == 500) {
					//系统错误
					common.msgError(result.message)
				} else if (result.code == 301) {
					//警告
					common.msgWarn(result.message);
				} else if (result.code == 2004) {
					//没有权限
					common.msgWarn(result.message);
				} else if (result.code == 2002) {
					//数据校验错误
					common.msgWarn(result.message);
				} else if (result.code == 2001) {
					//填写值不符合要求
					common.msgWarn(result.message);
				}
				return Promise.reject(response);
			}
		} else {
			return Promise.reject(response);
		}
	},
	error => {
		console.info("response",error)
		tryHideFullScreenLoading();
		common.msgError(error.message)
		return Promise.reject(error);
	}
);

export default {
	name: "http",

	upFileUrl: upFileUrl,
	upFilesUrl: upFilesUrl,
	getToken: getToken,
	uploadHeaders: uploadHeaders,
	//get请求
	get(url, params) {
		return axios.get(url, {
			params: params
		})
	},
	//post请求
	post(url, params) {
		return axios.post(url, params);
	},
	//put请求
	put(url, params) {
		return axios.put(url, params)
	},
	//put请求
	delete(url, params) {
		return axios.delete(url, {
			params: params
		})
	},
	//下载
	download(url, params) {
		return new Promise(() => {
			axios.post(url, Qs.stringify(params), {
					responseType: 'blob'
				})
				.then(res => {
					if (res.data.type == 'application/json') {
						let reader = new FileReader()
						reader.onload = function() {
							try {
								const jsonData = JSON.parse(reader.result); // 说明是普通对象数据，后台转换失败
								if (jsonData.code == 2003) {
									if (failureCount == 0) {
										localStorage.clear();
										sessionStorage.clear()
										//跳转登录页
										router.replace("/login");
										//提示信息
										common.msgWarn(jsonData.message)
										failureCount = 1

									} else {
										failureCount = 0
										refreshCount == 0 ? refreshCount = 1 : refreshCount = 0
									}
								} else if (jsonData.code == 403) {
									Message.warning(jsonData.message);
								} else if (jsonData.code == 301) {
									Message.warning(jsonData.message);
								} else if (jsonData.code == 500) {
									Message.error(jsonData.message);
								} else if (jsonData.code == 2004) {} else {
									resolve(res.data);
								}
								// dosomething……
							} catch (err) { // 解析成对象失败，说明是正常的文件流
								console.log('success...', err);
							}
						};
						reader.readAsText(res.data);
					} else {
						let blob = new Blob([res.data]);
						saveAs(blob, decodeURI("闫伟.zip"))
					}
				})
				.catch((e) => {
					console.log(e)
					common.msgError("网络错误,请稍后再试")
				})

		})
	},
	// 上传
	upload(url, params) {
		axios.defaults.headers['Content-Type'] = 'multipart/form-data'
		return axios.post(url, params)
	}
};